package com.snail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.mapper.BizUserTestDetailMapper;
import com.snail.model.dto.UserTestSubmitDTO;
import com.snail.model.pojo.BizUserTestDetail;
import com.snail.service.BizUserTestService;
import com.snail.model.pojo.BizUserTest;
import com.snail.mapper.BizUserTestMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Monica
* @description 针对表【biz_user_test(用户答题表)】的数据库操作Service实现
* @createDate 2025-07-16 10:22:25
*/
@Service
@RequiredArgsConstructor
public class BizUserTestServiceImpl extends ServiceImpl<BizUserTestMapper, BizUserTest>
    implements BizUserTestService {

    private final BizUserTestDetailMapper detailMapper;


    @Transactional
    public boolean submitOrUpdateTest(Integer userId, UserTestSubmitDTO dto) {
        if (dto.getAnswers() == null || dto.getAnswers().isEmpty()) return false;

        // 1. 插入主表 biz_user_test
        BizUserTest test = new BizUserTest();
        test.setUserId(userId);
        test.setStartTime(dto.getStartTime());
        test.setEndTime(dto.getEndTime());
        test.setTotalQuestions(dto.getTotalQuestions());
        test.setCorrectCount(dto.getCorrectCount());
        test.setTestName(dto.getTestName());
        test.setScore(dto.getScore());

        this.save(test); // insert
        Long testId = test.getId().longValue();

        // 2. 插入子表明细 biz_user_test_detail
        List<BizUserTestDetail> detailList = dto.getAnswers().stream().map(answer -> {
            BizUserTestDetail detail = new BizUserTestDetail();
            detail.setTestId(testId);
            detail.setQuestionId(answer.getQuestionId());
            detail.setUserAnswer(answer.getUserAnswer());
            detail.setIsCorrect(answer.getTestScore().compareTo(BigDecimal.ZERO) > 0); // 分数>0则视为正确
            detail.setScore(answer.getTestScore());
            return detail;
        }).collect(Collectors.toList());

        detailMapper.insertBatch(detailList);

        return true;
    }


    public List<BizUserTest> listByUserId(Long userId) {
        return this.lambdaQuery().eq(BizUserTest::getUserId, userId).orderByDesc(BizUserTest::getStartTime).list();
    }

    @Override
    @Transactional
    public boolean deleteTestById(Long testId) {
        // 先删子表
        detailMapper.delete(new QueryWrapper<BizUserTestDetail>().eq("test_id", testId));
        // 再删主表
        return this.removeById(testId);
    }


    public List<BizUserTestDetail> getTestDetail(Long testId) {
        return detailMapper.selectList(new QueryWrapper<BizUserTestDetail>().eq("test_id", testId));
    }

}




